<?php
class CoreController extends Controller
{
    public $layout='//layouts/column2';
    protected $_xsession;
    protected $_xcookies;
    public $staticsPath;
    public $debug = false;
    private $_assetsUrl = null;
    public $assetsUrl;
    public $cs;
    public $city_info;
    public $ccity;//用户输入的城市
    public function init(){


        $this->_xsession = new CHttpSession();
        $this->_xsession->open();
    }

    protected function beforeAction($action) {
        //$this->staticsPath = Yii::app()->assetManager->publish($assets);
        Yii::app()->theme = 'uuzhoumo';
        $assets = Yii::getPathOfAlias('application').DS.'statics'.DS;
        //在asset中建立一个不冲突文件夹 用来存放JS IMG 以及 CSS  2014 03 10
        //前台公共的静态文件
//        $this->staticsPath = Yii::app()->getAssetManager()->publish($assets, false, -1, YII_DEBUG);//强制生成
        $this->staticsPath = $this->getAssetsUrl();
        $this->cs = Yii::app()->clientScript;
        if(Yii::app()->user->id){
            $message = Xtutuquan::getUserEmail(Yii::app()->user->id,Yii::app()->user->getState('group_id'));
            Yii::app()->user->setState('message',$message);
        }
        //前台皮肤里的公共文件
//        $this->assetsUrl = $this->getAssetsUrl();






        return true;
    }
    protected function login(){
        //处理自动登陆   ,当cookie存在，且session不存在的情况下生成session
        if($this->_cookiesGet('auto') && is_null(Yii::app()->user->getState('user_auth'))){
            $value = explode('|',Xtutuquan::encryption($this->_cookiesGet('auto'),1));
            list($username,$ip) = $value;
            if($ip == Xtutuquan::getClientIP()){
                $criteria=new CDbCriteria;
//                $criteria->select='id,username,password,salt,loginnum,last_login_time,last_login_ip';  // only select the 'title' column
//                $criteria->select='id,username,password,salt,loginnum,last_login_time,last_login_ip';  // only select the 'title' column
                $criteria->condition= 'username=:username';
                $criteria->params=array(':username'=>$username);
                $user_info = User::model()->find($criteria);
                $user_info->loginnum = $user_info->loginnum+1;
                $user_info->last_login_time = time();

                Yii::app()->user->id = $user_info->id;
                $group_id = $user_info->group_id;
                $user_info->update();
                $message = Xtutuquan::getUserEmail($user_info->id,$group_id);
                $auth = array(
                    'id' =>$user_info->id,
                    'username'=>$user_info->username,
                    'last_login_time'=>time(),
                    'avatar_status'=>$user_info->avatar_status,  //是否有头像
                    'avatar_public'=>$user_info->avatar_public,
                    'bg_url'=>$user_info->bg,    //背景图的地址
                    'nick_name'=>$user_info->nick_name,  //昵称
                    'feeling'=>$user_info->feeling,  //心情
                    'info_status'=>$user_info->info_status,    //状态到第几了 0 1 2 3 完成
                    'is_domain'=>$user_info->is_domain,
                    'domain'=>$user_info->domain,
                );
                $event = Xtutuquan::getUserEvent($user_info->id);
                Yii::app()->user->setState('event',$event);
                Yii::app()->user->setState('message',$message);
                Yii::app()->user->setState('user_role',$user_info->role);
                Yii::app()->user->setState('role_salt',$user_info->role_salt);
                Yii::app()->user->setState('group_id',$group_id);
                Yii::app()->user->setState('user_auth',$auth);
            }
        }


        //检测session是否存在
        if(Yii::app()->user->getState('user_auth')){
            return 1;
        }else{
            return false;
        }
    }

    public function getAssetsUrl() {
        if($this->_assetsUrl === null) {
            $assetsPath = Yii::app()->theme->basePath . '/assets';
            if($this->debug === true)
                $this->_assetsUrl = Yii::app()->getAssetManager()->publish($assetsPath, false, -1, true);
            else
                $this->_assetsUrl = Yii::app()->getAssetManager()->publish($assetsPath, false, -1, false);
        }
        return $this->_assetsUrl;
    }

    /**
     * 2014 2 17
     */
    /**
     * 设置cookie
     */
    protected function _cookiesSet ($name = '', $value = '', $expire = 3600, $path = '', $domain = '', $secure = false)
    {
        $cookieSet = new CHttpCookie($name, $value);
        $expire && $cookieSet->expire = $expire;
        $path && $cookieSet->path = $path;
        $domain && $cookieSet->domain = $domain;
        $secure && $cookieSet->secure = $secure;
        Yii::app()->request->cookies[$name] = $cookieSet;
    }

    /**
     * 获取cookie
     */
    protected function _cookiesGet ($name, $once = false)
    {
        $cookie = Yii::app()->request->getCookies();
        if($cookie[$name]){
            $data = $cookie[$name]->value;
        }else{
            $data = '';
        }

        if ($once)
            unset($cookie[$name]);
        return $data;
    }

    /**
     * 清理cookie
     * @param  $name
     */
    protected function _cookiesRemove ($name)
    {
        $cookie = Yii::app()->request->getCookies();
        unset($cookie[$name]);
    }



    //显示错误
    public function showError($errors){
        $array = array();
        if($errors){
            foreach($errors as $key=>$value){
                foreach($value as $v){
                    $array[] = $v;
                }
            }
            return $array[0];
        }else{
            return true;
        }
    }
    //获取用户 角色的前端操作动作 返回  true  与 false;
    public function getRole($role,$role_salt,$action){
        if($role > 0){
            //加盐解密对比
            $jm = Xtutuquan::encryption($role_salt,1);
            $jm_arr = explode('|',$jm);
            if($role ==$jm_arr[1]){
                //匹配成功 去role表取得这个role的前台frontend 用于的权限
                $role_priv = RolePriv::model()->getRole($role,$action,'frontend');
                return $role_priv;
            }else{
                //永久封账号
                $user_info = User::model()->findByPk($jm_arr[0]);
                $user_info->status = 0;
                $user_info->update();
                Yii::app()->user->logout();
                //销毁cookie
                $this->_cookiesRemove('auto');
                $this->redirect(Yii::app()->homeUrl);
            }
        }
    }
    public function getCity(){
        $this->ccity = CHtml::encode(Yii::app()->request->getParam('city'));
        if(!$this->ccity){
            //1 获取IP信息
            $getIpInfo = Xtutuquan::getIpLookup();
            //拼音
            if($getIpInfo){
                $en_city = Xtutuquan::pinyin($getIpInfo['city']);
                //去表去寻找
                $city = CreateCity::model()->find('en_name=:en_name',array(':en_name'=>$en_city));
                if($city){
                    $this->redirect(array('index/index','city'=>$en_city));
                }else{//不存在
                    //去查看省表  取省里面的一个城市
                    $province = CreateCity::model()->find('province=:province',array(':province'=>$getIpInfo['province']));
                    if($province){
                        $this->redirect(array('index/index','city'=>$province->en_name));
                    }else{
                        $this->redirect(array('index/index','city'=>$en_city));
                    }
                }
            }else{
                $this->redirect(array('index/index','city'=>Yii::app()->params['DEFAULT_CITY']));
            }
        }
        $this->city_info = CreateCity::model()->find('en_name=:en_name',array(':en_name'=>$this->ccity));
        if(!$this->city_info){
            $this->redirect(array('index/index','city'=>Yii::app()->params['DEFAULT_CITY']));
        }
    }
    /**
     * 跳转页面 在基类中.
     * @author Asa_yang <88683231@qq.com>
     * @link http://www.hoohg.com/
     * @copyright Copyright &copy; 2011-2013 Hoohg Software LLC
     * @param string $message 弹窗提示文字 .
     * @param string $status 状态,为  success.
     * @param integer $time 跳转时间
     * @param string $url  跳转地址
     * @return html 返回弹窗界面
     */
    public function redirect_message($message='操作成功',$status='success',$time=3,$url=false){

        $back_color ='#ff0000';
        if($status =='success'){
            $back_color= 'blue';
        }elseif($status == 'error'){
            $back_color= 'red';
        }
        if(is_array($url)){
            $route=isset($url[0]) ? $url[0] : '';
            $url=$this->createUrl($route,array_splice($url,1));
        }
        if ($url)
        {
            $url = "window.location.href='{$url}'";
        }
        else
        {
            $url = "history.back();";
        }


        echo <<<HTML
			<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
			<html>
			<head>
			<title>页面提示</title>
			<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
			<style type="text/css" rel="stylesheet">
			body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, textarea, p, blockquote, th, td, img, input, select {margin:0; padding:0;}
			dl, dt, dd, ul, ol, li{list-style:none; list-style-position:outside;}
			li, img {vertical-align:bottom;}
			.clear {font-size:0; line-height:0; height:0; clear:both; overflow:hidden;}
			.clearfix:after {clear: both;content: ".";display: block; height: 0;visibility: hidden;}
			* html .clearfix             { zoom: 1; } /* IE6 */
			*:first-child+html .clearfix { zoom: 1; } /* IE7 */
			/*全局*/
			body {background:#F4F4F4}
			.main {width:500px; position:absolute;left:50%; top:20%; margin:0 0 0 -250px; background:#FFFFFF; border:1px solid #DEDEDE; border-radius:5px; box-shadow:0 1px 3px #CCCCCC; padding:20px}
			h1 {font:normal 25px/50px "microsoft yahei"; color:#0085CC; margin:0 0 10px 0}
			#blue {color:#0085CC;}
			#red {color:-moz-activehyperlinktext};
			p {font:normal 14px/23px "microsoft yahei"; color:#797979}
			p a {margin:0 2px; color:#0055CC}
			</style>
			</head>
			<body >
				<div class="main">
				<h1 id="{$back_color}">{$message}</h1><br/><p>页面将在<span id="sec" style="color:{$back_color};">{$time}</span>秒内自动跳转，如果不想等待，请点击 <a href="javascript:history.back(-1);">这里</a>跳转。</p>
				<script type="text/javascript">
					var timer;
                    function run(){
                        var s = document.getElementById("sec");
                        if(s.innerHTML == 0){
                        	clearInterval(timer);
                        	{$url}
                            return false;
                        }
                        s.innerHTML = s.innerHTML * 1 - 1;

                    }
                    timer = window.setInterval("run();", 1000);
                </script>
			</div>
			</body>
			</html>

HTML;
        exit;

    }
}